<template>
    <view class="booking">
        <!-- 顶部轮播图 -->
        <swiper class="banner" circular autoplay interval="3000" duration="500">
            <swiper-item v-for="(item, index) in bannerList" :key="index">
                <image :src="item" mode="aspectFill"></image>
            </swiper-item>
        </swiper>

        <!-- 预约表单区域 -->
        <view class="form-container">
            <!-- 切换按钮 -->
            <view class="switch-buttons">
                <view class="btn" :class="{ active: bookingType === '1' }" @tap="bookingType = '1'">预约接站
                </view>
                <view class="btn" :class="{ active: bookingType === '2' }" @tap="bookingType = '2'">预约送站
                </view>
            </view>

            <!-- 表单内容 -->
            <view class="form">
                <!-- 车站选择 -->
                <view class="form-item">
                    <text class="label">车站名称</text>
                    <picker class="input-wrapper" @change="handleStationChange" :value="formData.stationId"
                        :range="stations" range-key="stationName">
                        <view class="picker">
                            {{formData.stationId ? (stations.find(s => s.id === formData.stationId)?.stationName ||
                                '请选择') : '请选择'}}
                            <text class="arrow">></text>
                        </view>
                    </picker>
                </view>

                <!-- 到达时间 -->
                <view class="form-item">
                    <text class="label" v-if="bookingType === '1'">到站时间</text>
                    <text class="label" v-if="bookingType === '2'">用车时间</text>
                    <view class="input-wrapper" @tap="showDateTimePicker">
                        <view class="picker">
                            {{ formattedDateTime || '请选择' }}
                            <text class="arrow">></text>
                        </view>
                    </view>
                </view>

                <!-- 底部时间选择器 -->
                <view class="datetime-picker" v-if="showPicker">
                    <view class="mask" @tap="hideDateTimePicker"></view>
                    <view class="picker-content">
                        <view class="picker-header">
                            <text class="cancel" @tap="hideDateTimePicker">取消</text>
                            <text class="title">选择用车时间</text>
                            <text class="confirm" @tap="confirmDateTime">确定</text>
                        </view>
                        <view class="picker-body">
                            <picker-view :value="dateTimeIndex" @change="handlePickerChange" class="picker-view"
                                :indicator-style="indicatorStyle">
                                <picker-view-column class="date-column">
                                    <view class="picker-item" v-for="(date, index) in dateList" :key="index">
                                        {{ date.month }}月{{ date.day }}日({{ date.week }})
                                    </view>
                                </picker-view-column>
                                <picker-view-column class="time-column">
                                    <view class="picker-item" v-for="hour in hourList" :key="hour">
                                        {{ hour }}时
                                    </view>
                                </picker-view-column>
                                <picker-view-column class="time-column">
                                    <view class="picker-item" v-for="minute in minuteList" :key="minute">
                                        {{ minute }}分
                                    </view>
                                </picker-view-column>
                            </picker-view>
                        </view>
                    </view>
                </view>

                <!-- 房间号(仅送站时显示) -->
                <view class="form-item" v-if="bookingType === '2'">
                    <text class="label">房间号码</text>
                    <view class="input-wrapper">
                        <input type="text" v-model="formData.roomNo" placeholder="请输入房间号" />
                    </view>
                </view>
                <view class="form-item" v-if="bookingType === '1'">
                    <text class="label">入住时间</text>
                    <view class="input-wrapper" @tap="openCheckInPicker">
                        <view class="picker">
                            {{ formData.bookingTime || '请选择入住时间' }}
                            <text class="arrow">></text>
                        </view>
                    </view>
                </view>

                <view class="form-item">
                    <text class="label">乘客姓名</text>
                    <view class="input-wrapper">
                        <input type="text" v-model="formData.username" placeholder="请输入乘客姓名" maxlength="11" />
                    </view>
                </view>

                <!-- 联系方式 -->
                <view class="form-item">
                    <text class="label">联系方式</text>
                    <view class="input-wrapper">
                        <input type="number" v-model="formData.phone" placeholder="请输入手机号" maxlength="11" />
                    </view>
                </view>

                <!-- 人数选择 -->
                <view class="form-item">
                    <text class="label">出行人数</text>
                    <view class="input-wrapper">
                        <view class="number-picker">
                            <text class="btn minus" @tap="handleNumberChange(-1)">-</text>
                            <text class="number">{{ formData.personCount }}</text>
                            <text class="btn plus" @tap="handleNumberChange(1)">+</text>
                        </view>
                    </view>
                </view>

                <!-- 备注 -->
                <view class="form-item">
                    <text class="label">备注</text>
                    <view class="input-wrapper">
                        <textarea v-model="formData.remark" placeholder="请输入备注信息" maxlength="200" />
                    </view>
                </view>
            </view>

            <!-- 提交按钮 -->
            <button class="submit-btn" @tap="handleSubmit">确认预约</button>
        </view>

        <!-- 手机号授权弹框 -->
        <phone-auth :show="showPhoneAuth" @success="handlePhoneAuthSuccess" @fail="handlePhoneAuthCancel"
            @cancel="handlePhoneAuthCancel" />

        <!-- 入住时间选择器 -->
        <view class="datetime-picker" v-if="showCheckInPicker">
            <view class="mask" @tap="closeCheckInPicker"></view>
            <view class="picker-content">
                <view class="picker-header">
                    <text class="cancel" @tap="closeCheckInPicker">取消</text>
                    <text class="title">选择入住时间</text>
                    <text class="confirm" @tap="confirmCheckInTime">确定</text>
                </view>
                <view class="picker-body">
                    <picker-view 
                        :value="checkInDateIndex" 
                        @change="handleCheckInDateChange" 
                        class="picker-view"
                        :indicator-style="indicatorStyle"
                    >
                        <picker-view-column>
                            <view class="picker-item" v-for="(date, index) in checkInDateList" :key="index">
                                {{ date.month }}月{{ date.day }}日
                            </view>
                        </picker-view-column>
                    </picker-view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { homeApi, bookingApi } from '@/api'
import { userStorage } from '@/utils/storage'
import PhoneAuth from '@/components/phone-auth/index.vue'

export default {
    components: {
        PhoneAuth
    },
    data() {
        return {
            bookingType: '1', // pickup: 接站, dropoff: 送站
            bannerList: [],
            stations: [],
            showPicker: false,
            dateTimeIndex: [0, 0, 0],
            dateList: [],
            indicatorStyle: 'height: 88rpx;',
            hourList: [],
            minuteList: [],
            visibleHourCount: 5, // 可见小时数量
            visibleMinuteCount: 5, // 可见分钟数量
            tempDateTime: new Date(),
            formData: {
                id: '',
                stationId: '',
                arrivalTime: '',
                roomNo: '',
                username: '',
                phone: '',
                personCount: 1,
                remark: '',
                bookingTime: ''
            },
            isEdit: false, // 是否是编辑模式
            editData: null, // 编辑的数据
            showPhoneAuth: false,
            showCheckInPicker: false,
            checkInDateIndex: [0],
            checkInDateList: [],
        }
    },
    computed: {
        formattedDateTime() {
            if (!this.formData.arrivalTime) return ''
            const date = new Date(this.formData.arrivalTime)
            const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()]
            return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}时${String(date.getMinutes()).padStart(2, '0')}分`
        }
    },
    created() {
        this.initDateTimeList()
        this.initCheckInDateList()
    },
    onShow() {
        // 检查是否有编辑数据
        const editData = uni.getStorageSync('editBookingData')
        if (editData) {
            this.isEdit = true
            this.editData = editData
            // 回显数据
            this.bookingType = editData.type
            this.formData = {
                id: editData.id,
                stationId: editData.stationId,
                arrivalTime: editData.arrivalTime,
                roomNo: editData.roomNo || '',
                username: editData.username || '',
                phone: editData.phone,
                personCount: Number(editData.personCount),
                remark: editData.remark || '',
                bookingTime: editData.bookingTime || ''
            }
            // 清除存储的编辑数据
            uni.removeStorageSync('editBookingData')
        } else {
            this.isEdit = false
            this.editData = null
            // 重置表单
            this.resetForm()
        }
        this.getBannerList()
        this.getStations()
    },
    methods: {
        // 获取轮播图
        getBannerList() {
            homeApi.getBannerList({
                categoryId: 3
            }).then(res => {
                this.bannerList = []
                res.data.forEach(item => {
                    this.bannerList.push(this.$baseUrl + item.imageUrl)
                })
            })
        },
        // 获取车站列表
        getStations() {
            bookingApi.getStationList().then(res => {
                this.stations = res.data
            })
        },
        // 初始化日期时间列表
        initDateTimeList() {
            const now = new Date()
            // 生成未来60天的日期列表
            this.dateList = Array.from({ length: 60 }, (_, i) => {
                const date = new Date(now.getTime() + i * 24 * 60 * 60 * 1000)
                return {
                    month: date.getMonth() + 1,
                    day: date.getDate(),
                    week: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()],
                    fullDate: date
                }
            })

            // 生成小时列表 (0-23)
            this.hourList = Array.from({ length: 24 }, (_, i) =>
                String(i).padStart(2, '0')
            )

            // 生成分钟列表 (0-59)
            this.minuteList = Array.from({ length: 60 }, (_, i) =>
                String(i).padStart(2, '0')
            )
        },

        // 显示时间选择器
        showDateTimePicker() {
            this.showPicker = true
            if (this.formData.arrivalTime) {
                // 如果已有选择时间，显示已选时间
                const date = new Date(this.formData.arrivalTime)
                const dayIndex = this.dateList.findIndex(d =>
                    d.month === date.getMonth() + 1 && d.day === date.getDate()
                )
                this.dateTimeIndex = [
                    dayIndex > -1 ? dayIndex : 0,
                    date.getHours(),
                    date.getMinutes()
                ]
            } else {
                // 默认显示当前时间
                const now = new Date()
                this.dateTimeIndex = [
                    0,
                    now.getHours(),
                    now.getMinutes()
                ]
            }
        },

        // 隐藏时间选择器
        hideDateTimePicker() {
            this.showPicker = false
        },

        // 处理选择器变化
        handlePickerChange(e) {
            const values = e.detail.value
            this.dateTimeIndex = values

            const selectedDate = this.dateList[values[0]].fullDate
            const selectedHour = parseInt(this.hourList[values[1]])
            const selectedMinute = parseInt(this.minuteList[values[2]])

            this.tempDateTime = new Date(
                selectedDate.getFullYear(),
                selectedDate.getMonth(),
                selectedDate.getDate(),
                selectedHour,
                selectedMinute
            )
        },

        // 确认选择
        confirmDateTime() {
            if (this.tempDateTime && this.tempDateTime < new Date()) {
                uni.showToast({
                    title: '请选择未来的时间',
                    icon: 'none'
                })
                return
            }
            this.formData.arrivalTime = this.tempDateTime.toISOString()
            this.hideDateTimePicker()
        },
        // 处理车站选择
        handleStationChange(e) {
            const index = e.detail.value
            this.formData.stationId = this.stations[index].id
        },
        // 处理人数变化
        handleNumberChange(delta) {
            const newCount = this.formData.personCount + delta
            if (newCount >= 1 && newCount <= 10) {
                this.formData.personCount = newCount
            }
        },
        // 重置表单
        resetForm() {
            this.formData = {
                stationId: '',
                arrivalTime: '',
                roomNo: '',
                username: '',
                phone: '',
                personCount: 1,
                remark: '',
                bookingTime: ''
            }
            const userInfo = userStorage.getUserInfo()
            this.formData.phone = userInfo.userPhone
        },
        // 提交预约
        handleSubmit() {
            if (!this.formData.stationId) {
                uni.showToast({
                    title: '请选择车站',
                    icon: 'none'
                })
                return
            }
            if (!this.formData.arrivalTime) {
                uni.showToast({
                    title: '请选择到达时间',
                    icon: 'none'
                })
                return
            }
            if (this.bookingType === '2' && !this.formData.roomNo) {
                uni.showToast({
                    title: '请输入房间号',
                    icon: 'none'
                })
                return
            }
            if (!this.formData.username) {
                uni.showToast({
                    title: '请输入乘客姓名',
                    icon: 'none'
                })
                return
            }
            if (!this.formData.phone) {
                uni.showToast({
                    title: '请输入联系方式',
                    icon: 'none'
                })
                return
            }
            if (!/^1\d{10}$/.test(this.formData.phone)) {
                uni.showToast({
                    title: '请输入正确的手机号',
                    icon: 'none'
                })
                return
            }

            const data = {
                ...this.formData,
                type: this.bookingType
            }

            // 格式化日期时间
            if (data.arrivalTime) {
                const date = new Date(data.arrivalTime)
                // 格式化为 YYYY-MM-DD HH:mm:ss
                data.arrivalTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:00`
            }

            data.userPhone = userStorage.getUserInfo().userPhone
            data.wxUserName = userStorage.getUserInfo().username
            const api = this.isEdit ? 'updateBooking' : 'submitBooking'


            userStorage.checkPhoneAuth().then(() => {
                uni.showLoading({
                    title: this.isEdit ? '修改中...' : '提交中...'
                })
                bookingApi[api](data).then(res => {
                    uni.hideLoading()
                    uni.showToast({
                        title: this.isEdit ? '修改成功' : '预约成功',
                        icon: 'success'
                    })
                    this.resetForm()
                    if (this.isEdit) {
                        uni.navigateTo({
                            url: '/pages/booking-list/index'
                        })
                    }
                })
            }).catch(err => {
                if (err.message === '需要手机号授权') {
                    this.showPhoneAuth = true
                } else {
                    uni.showToast({
                        title: err.message,
                        icon: 'none'
                    })
                }
            })
        },
        // 手机号授权成功
        handlePhoneAuthSuccess() {
            this.showPhoneAuth = false
            this.handleSubmit()
        },
        // 手机号授权取消
        handlePhoneAuthCancel() {
            this.showPhoneAuth = false
        },
        // 显示入住时间选择器
        openCheckInPicker() {
            this.showCheckInPicker = true
        },
        // 隐藏入住时间选择器
        closeCheckInPicker() {
            this.showCheckInPicker = false
        },
        // 处理入住日期变化
        handleCheckInDateChange(e) {
            const values = e.detail.value
            this.checkInDateIndex = values
        },
        // 确认入住时间
        confirmCheckInTime() {
            const selectedDate = this.checkInDateList[this.checkInDateIndex[0]].date
            const date = new Date(selectedDate)
            
            // 格式化为 YYYY-MM-DD
            this.formData.bookingTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
            this.closeCheckInPicker()
        },
        // 初始化入住日期列表
        initCheckInDateList() {
            const now = new Date()
            const dateList = []
            // 生成未来30天的日期
            for (let i = 0; i < 30; i++) {
                const date = new Date(now.getTime() + i * 24 * 60 * 60 * 1000)
                dateList.push({
                    month: date.getMonth() + 1,
                    day: date.getDate(),
                    date: date
                })
            }
            this.checkInDateList = dateList
        }
    }
}
</script>

<style lang="scss">
.booking {
    min-height: 100vh;
    background-color: #fff;
    position: relative;

    .banner {
        width: 100%;
        height: 400rpx;

        image {
            width: 100%;
            height: 100%;
        }
    }

    .form-container {
        position: absolute;
        top: 320rpx;
        left: 20rpx;
        right: 20rpx;
        bottom: 20rpx;
        padding: 30rpx;
        background-color: #fff;
        border-radius: 40rpx 40rpx 0 0;
        box-shadow:
            0 -8rpx 20rpx rgba(0, 0, 0, 0.03),
            0 -4rpx 12rpx rgba(0, 0, 0, 0.06),
            0 -2rpx 4rpx rgba(0, 0, 0, 0.08);
        z-index: 1;

        border: 2rpx solid rgba(0, 0, 0, 0.02);

        background: linear-gradient(to bottom, #ffffff, #fafafa);

        overflow-y: auto;
        -webkit-overflow-scrolling: touch;

        .switch-buttons {
            display: flex;
            margin-bottom: 40rpx;

            .btn {
                flex: 1;
                height: 80rpx;
                line-height: 80rpx;
                text-align: center;
                font-size: 32rpx;
                color: #999;
                background-color: #f8f8f8;

                &:first-child {
                    border-radius: 40rpx 0 0 40rpx;
                }

                &:last-child {
                    border-radius: 0 40rpx 40rpx 0;
                }

                &.active {
                    color: #fff;
                    background: linear-gradient(to right, #1989fa, #39b9fa);
                    box-shadow: 0 4rpx 8rpx rgba(25, 137, 250, 0.2);
                }
            }
        }

        .form {
            .form-item {
                margin-bottom: 30rpx;
                display: flex;
                align-items: flex-start;

                .label {
                    width: 160rpx;
                    font-size: 28rpx;
                    color: #333;
                    padding-top: 24rpx;
                }

                .input-wrapper {
                    flex: 1;

                    .picker,
                    input,
                    textarea,
                    .number-picker {
                        background-color: #f8f8f8;
                        border-radius: 10rpx;
                        box-shadow: inset 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
                        border: 2rpx solid #f0f0f0;
                    }

                    .picker {
                        height: 80rpx;
                        line-height: 80rpx;
                        padding: 0 20rpx;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;

                        .arrow {
                            color: #999;
                        }
                    }

                    input {
                        width: 100%;
                        height: 80rpx;
                        padding: 0 20rpx;
                        font-size: 28rpx;
                        box-sizing: border-box;
                    }

                    textarea {
                        width: 100%;
                        height: 160rpx;
                        padding: 20rpx;
                        font-size: 28rpx;
                        box-sizing: border-box;
                    }

                    .number-picker {
                        display: flex;
                        align-items: center;
                        height: 80rpx;
                        padding: 0 20rpx;

                        .btn {
                            width: 60rpx;
                            height: 60rpx;
                            line-height: 60rpx;
                            text-align: center;
                            background-color: #fff;
                            border-radius: 50%;
                            color: #666;
                        }

                        .number {
                            margin: 0 30rpx;
                            font-size: 32rpx;
                            color: #333;
                        }
                    }
                }
            }
        }

        .submit-btn {
            width: 100%;
            height: 88rpx;
            line-height: 88rpx;
            text-align: center;
            color: #fff;
            font-size: 32rpx;
            background: linear-gradient(to right, #1989fa, #39b9fa);
            box-shadow: 0 4rpx 12rpx rgba(25, 137, 250, 0.3);
            border-radius: 44rpx;
            margin-top: 40rpx;

            &:active {
                transform: translateY(2rpx);
                box-shadow: 0 2rpx 8rpx rgba(25, 137, 250, 0.2);
            }
        }
    }

    .datetime-picker {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        z-index: 100;

        .mask {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .picker-content {
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #fff;
            border-radius: 24rpx 24rpx 0 0;

            .picker-header {
                display: flex;
                align-items: center;
                height: 100rpx;
                padding: 0 30rpx;
                border-bottom: 2rpx solid #f5f5f5;

                .cancel {
                    color: #999;
                    font-size: 32rpx;

                    &:active {
                        opacity: 0.7;
                    }
                }

                .title {
                    flex: 1;
                    text-align: center;
                    font-size: 32rpx;
                    font-weight: bold;
                    color: #333;
                }

                .confirm {
                    color: #1989fa;
                    font-size: 32rpx;

                    &:active {
                        opacity: 0.7;
                    }
                }
            }

            .picker-body {
                height: 480rpx;

                .picker-view {
                    height: 100%;

                    .date-column {
                        flex: 2;
                    }

                    .time-column {
                        flex: 1;
                    }

                    .picker-item {
                        height: 88rpx;
                        line-height: 88rpx;
                        text-align: center;
                        font-size: 32rpx;
                        color: #333;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        padding: 0 10rpx;
                    }
                }
            }
        }
    }
}
</style>